from odoo import fields, models, _
from odoo.exceptions import ValidationError
from odoo.tools import float_compare


class StockMove(models.Model):
    _inherit = 'stock.move'

    def _action_done(self, cancel_backorder=False):
        res = super()._action_done(cancel_backorder)
        for move in self.filtered(lambda x: x.state == 'done'):
            if not move.product_id.s_required_iqc:
                continue
            for line in move.move_line_ids:
                if line.location_id.usage == 'supplier' and line.location_dest_id.usage == 'internal':
                    if not line.quality_check_ids:
                        raise ValidationError(_('Raw material% s requires quality inspection upon receipt, please send a quality inspection notification first!', line.product_id.name))
                    pass_qty = sum(line.quality_check_ids.filtered(lambda x: x.quality_state == 'pass').mapped('qty_line'))
                    if float_compare(pass_qty, line.quantity, precision_rounding=line.product_id.uom_id.rounding) == -1:
                        raise ValidationError(_('Product: %s incoming %.3f Cannot exceed the number of good products in quality inspection %.3f', line.product_id.name, line.quantity, pass_qty))
        return res